package com.hy.ruiji.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hy.ruiji.common.R;
import com.hy.ruiji.enyity.User;
import com.hy.ruiji.service.UserService;
import com.hy.ruiji.utils.SMSUtils;
import com.hy.ruiji.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送手机短信验证码
     * @param user 需要发送的手机号
     * @return 返回验证码
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(HttpSession session, @RequestBody User user){
        //获取手机号
        String phone = user.getPhone();
        //判断手机号不为空
        if(StringUtils.isNotEmpty(phone)){
            //调用工具类生成四位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码是："+code);
            //调用工具类发送短信
            //SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code);
            //把验证码保存到session与前端做比对
            session.setAttribute(phone,code);
            return R.success("手机验证码短信发送成功");
        }
        return R.error("短信发送失败");
    }

    /**
     * 用户登录和注册
     * @param map 封装的手机号和验证码
     * @param session 把手机号放到session里面
     * @return 返回登录结果
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        //获取session里面的验证码
        Object codeInSession = session.getAttribute(phone);
        //比对验证码是否成功
        if(codeInSession!=null&&codeInSession.equals(code)){
            //判断用户是否注册
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone,phone);
            User user=userService.getOne(wrapper);
            if(user==null){
                //当前用户未注册
                user=new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //把用户id放到session里面
            session.setAttribute("user",user.getId());
            return R.success(user);
        }
        return R.error("登录失败！");
    }

    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session){
        session.removeAttribute("user");
        return R.success("退出成功");
    }
}
